package com.cy.mall.service.order.impl;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.cy.mall.comm.utils.JsonObjectMapper;
import com.cy.mall.comm.utils.RSAUtils;
import com.cy.mall.comm.utils.SpringContextUtils;
import com.cy.mall.dao.mapper.brand.BrandMapper;
import com.cy.mall.dao.mapper.customer.*;
import com.cy.mall.dao.mapper.product.ProductMapper;
import com.cy.mall.dao.mapper.store.StoreMapper;
import com.cy.mall.model.PageBean;
import com.cy.mall.model.ao.order.*;
import com.cy.mall.model.domain.brand.Brand;
import com.cy.mall.model.domain.customer.*;
import com.cy.mall.model.domain.store.Store;
import com.cy.mall.model.dto.fujue.req.*;
import com.cy.mall.model.dto.fujue.resp.LoanApplyDataDTO;
import com.cy.mall.model.dto.fujue.resp.LoanDataDTO;
import com.cy.mall.model.dto.fujue.resp.NotifyDataDTO;
import com.cy.mall.model.dto.product.ProductInfoDTO;
import com.cy.mall.model.enums.ResultCode;
import com.cy.mall.model.enums.ThirdSource;
import com.cy.mall.model.enums.customer.CustomerIdCardAuthStatus;
import com.cy.mall.model.enums.order.*;
import com.cy.mall.model.query.order.OrderListQuery;
import com.cy.mall.model.vo.order.*;
import com.cy.mall.service.dict.DictService;
import com.cy.mall.service.fujue.FujueApiService;
import com.cy.mall.service.order.OrderAuditService;
import com.cy.mall.service.order.OrderStatusService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.cy.mall.comm.constant.Constants;
import com.cy.mall.comm.utils.CommonUtils;
import com.cy.mall.dao.mapper.order.OrderAuditRecordMapper;
import com.cy.mall.dao.mapper.order.OrderGoodsExtraInfoMapper;
import com.cy.mall.dao.mapper.order.OrderImageMapper;
import com.cy.mall.dao.mapper.order.OrderMapper;
import com.cy.mall.model.Result;
import com.cy.mall.model.ao.customer.CustomerContactAddAO;
import com.cy.mall.model.ao.customer.CustomerImageAddAO;
import com.cy.mall.model.domain.order.Order;
import com.cy.mall.model.domain.order.OrderGoodsExtraInfo;
import com.cy.mall.model.domain.order.OrderImage;
import com.cy.mall.model.dto.customer.CustomerLoginDTO;
import com.cy.mall.model.dto.customer.ValidateFaceIdResultDTO;
import com.cy.mall.model.enums.CheckResult;
import com.cy.mall.model.enums.Process;
import com.cy.mall.model.enums.customer.CustomerImageType;
import com.cy.mall.model.vo.customer.CustomerContactInfoVO;
import com.cy.mall.model.vo.customer.CustomerImageListVO;
import com.cy.mall.service.BaseService;
import com.cy.mall.service.order.OrderService;


/**
 * 订单模块服务
 *
 * @author tanyilin
 *
 * @create 2019年2月26日 上午10:00:27
 */
@Slf4j
@Service
public class OrderServiceImpl extends BaseService implements OrderService {

	@Autowired
	private OrderMapper orderMapper;
	@Autowired
	private OrderAuditRecordMapper orderAuditRecordMapper;
	@Autowired
	private OrderGoodsExtraInfoMapper orderGoodsExtraInfoMapper;
	@Autowired
	private OrderImageMapper orderImageMapper;
	@Autowired
	private CustomerMapper                 customerMapper;
	@Autowired
	private CustomerContactMapper          customerContactMapper;
	@Autowired
	private CustomerImageMapper            customerImageMapper;
	@Autowired
	private ProductMapper                  productMapper;
	@Autowired
	private OrderStatusService             orderStatusService;
	@Autowired
	private BrandMapper                    brandMapper;
	@Autowired
	private StoreMapper                    storeMapper;
	@Autowired
	private DictService                    dictService;
	@Autowired
	private CustomerIdCardAuthRecordMapper customerIdCardAuthRecordMapper;
    @Autowired
    private CustomerHouseInfoMapper        customerHouseInfoMapper;
    @Autowired
    private FujueApiService fujueApiService;
    @Autowired
	private CustomerBankMapper customerBankMapper;

	
	@Override
	@Transactional
	public Result addOrder(OrderAddAO addAO, CustomerLoginDTO loginCustomer) {
		
		Date time = new Date();
		Long orderId = 0L;
		Long customerId = loginCustomer.getCustomerId();
		String mobile = loginCustomer.getMobile();
		
		//先验证客户有没有完成人脸识别验证
		ValidateFaceIdResultDTO validateFaceIdResultDTO = customerMapper.selectValidateFaceIdResultDTO(customerId);
		state(validateFaceIdResultDTO != null, "验证客户是否已完成人脸识别，异常");
		state(CheckResult.PASS.equals(validateFaceIdResultDTO.getFaceidCheckResult()), "客户未完成人脸识别验证流程");
		
		//新增订单信息
		Order newOrder = new Order();
		BeanUtils.copyProperties(addAO, newOrder);
		newOrder.setCustomerId(customerId);
		newOrder.setProductId(Constants.JYD_PRODUCTID);
		//默认深圳
		newOrder.setCityId(1L);
		newOrder.setMobile(mobile);
		newOrder.setOrderStatus(OrderStatus.APPLY_SUCCESS);
		newOrder.setApplyStatus(ApplyStatus.PROCESSING);
		newOrder.setUserId(0L);
		newOrder.setCommissionStatus(CommissionStatus.UN_NEED);
		newOrder.setWithholdStatus(OrderWithholdStatus.UN_NEED);
		newOrder.setCreateTime(time);
		newOrder.setUpdateTime(time);
		newOrder.setRejectType(OrderRejectType.UN_REJECT);
		//插入数据
		orderMapper.insertSelective(newOrder);
		//得到orderId
		orderId = newOrder.getId();
		
		//新增家具分期订单额外信息
		OrderGoodsExtraInfo orderGoodsExtraInfo = new OrderGoodsExtraInfo();
		BeanUtils.copyProperties(addAO, orderGoodsExtraInfo);
		orderGoodsExtraInfo.setOrderId(orderId);
		orderGoodsExtraInfo.setCreateTime(time);
		orderGoodsExtraInfo.setUpdateTime(time);
		orderGoodsExtraInfoMapper.insertSelective(orderGoodsExtraInfo);
		
		//新增订单购买证明
		List<OrderImageAddAO> purchaseProofList = addAO.getPurchaseProofList();
		if(!CommonUtils.isEmpty(purchaseProofList)) {
			List<OrderImage> orderImageList = new ArrayList<>();
			for(OrderImageAddAO orderImageAddAO : purchaseProofList) {
				OrderImage orderImage = new OrderImage();
				orderImage.setOrderId(orderId);
				orderImage.setType(orderImageAddAO.getType());
				orderImage.setPath(orderImageAddAO.getPath());
				orderImage.setCreateTime(time);
				orderImage.setUpdateTime(time);
				orderImageList.add(orderImage);
			}
			//批量新增
			orderImageMapper.insertBatch(orderImageList);
			//删除无效数据
			orderImageMapper.deleteByUpdateTime(orderId, OrderImageType.PURCHASE_PROOF, time);
		}
		
		//添加第一条订单审核数据类型，‘申请成功’
		String remark = "通过";
		SpringContextUtils.getBean(OrderAuditService.class).addOrderAuditRecord(orderId, Process.APPLY, AuditResult.PASS, remark);

    	//更新客户信息
    	Customer updateCustomer = new Customer();
    	BeanUtils.copyProperties(addAO, updateCustomer);
    	updateCustomer.setId(customerId);
    	updateCustomer.setUpdateTime(time);
    	customerMapper.updateByPrimaryKeySelective(updateCustomer);
    	
    	//更新客户联系人信息 
    	List<CustomerContactAddAO> contactList = addAO.getContactList();
    	if(!CommonUtils.isEmpty(contactList)) {
    		List<CustomerContact> customerContactList = new ArrayList<>();
    		for(CustomerContactAddAO customerContactAddAO : contactList) {
    			CustomerContact customerContact = new CustomerContact();
    			BeanUtils.copyProperties(customerContactAddAO, customerContact);
    			customerContact.setCustomerId(customerId);
    			customerContact.setCreateTime(time);
    			customerContact.setUpdateTime(time);
    			customerContactList.add(customerContact);
    		}
    		//批量新增
    		customerContactMapper.insertBatch(customerContactList);
    		//删除无效数据
    		customerContactMapper.deleteByUpdateTime(customerId, time);
    	}
    	
    	//更新客户房产证明图片
    	List<CustomerImageAddAO> housePropertyProofList = addAO.getHousePropertyProofList();
    	if(!CommonUtils.isEmpty(housePropertyProofList)) {
    		List<CustomerImage> customerImageList = new ArrayList<>();
    		for(CustomerImageAddAO customerImageAddAO : housePropertyProofList) {
    			CustomerImage customerImage = new CustomerImage();
    			BeanUtils.copyProperties(customerImageAddAO, customerImage);
    			customerImage.setCustomerId(customerId);
    			customerImage.setCreateTime(time);
    			customerImage.setUpdateTime(time);
    			customerImageList.add(customerImage);
    		}
    		//批量新增
    		customerImageMapper.insertBatch(customerImageList);
    		//删除无效数据
    		customerImageMapper.deleteByUpdateTime(customerId, CustomerImageType.HOUSE_PROPERTY_PROOF, time);
    	}
    	
    	//更新客户结婚证明图片
    	List<CustomerImageAddAO> marriageProofList = addAO.getMarriageProofList();
    	if(!CommonUtils.isEmpty(marriageProofList)) {
    		List<CustomerImage> customerImageList = new ArrayList<>();
    		for(CustomerImageAddAO customerImageAddAO : marriageProofList) {
    			CustomerImage customerImage = new CustomerImage();
    			BeanUtils.copyProperties(customerImageAddAO, customerImage);
    			customerImage.setCustomerId(customerId);
    			customerImage.setCreateTime(time);
    			customerImage.setUpdateTime(time);
    			customerImageList.add(customerImage);
    		}
    		//批量新增
    		customerImageMapper.insertBatch(customerImageList);
    		//删除无效数据
    		customerImageMapper.deleteByUpdateTime(customerId, CustomerImageType.MARRIAGE_PROOF, time);
    	}
    	
    	
		
		return Result.success("新增订单成功", orderId);
	}

	@Override
	@Transactional
	public Result editOrder(OrderEditAO editAO, CustomerLoginDTO loginCustomer) {
		
		Date time = new Date();
		Long orderId = editAO.getOrderId();
		Long customerId = loginCustomer.getCustomerId();
		
		//更新订单信息
		Order updateOrder = new Order();
		BeanUtils.copyProperties(editAO, updateOrder);
		updateOrder.setId(orderId);
		updateOrder.setUpdateTime(time);
		orderMapper.updateByPrimaryKeySelective(updateOrder);
		
		//更新家具分期订单额外信息表
		OrderGoodsExtraInfo dbOrderGoodsExtraInfo = new OrderGoodsExtraInfo();
		dbOrderGoodsExtraInfo.setOrderId(orderId);
		dbOrderGoodsExtraInfo =	orderGoodsExtraInfoMapper.selectOne(dbOrderGoodsExtraInfo);
		state(dbOrderGoodsExtraInfo != null, "家具分期订单信息异常");
		OrderGoodsExtraInfo updateOrderGoodsExtraInfo = new OrderGoodsExtraInfo();
		BeanUtils.copyProperties(editAO, updateOrderGoodsExtraInfo);
		updateOrderGoodsExtraInfo.setId(dbOrderGoodsExtraInfo.getId());
		updateOrderGoodsExtraInfo.setUpdateTime(time);
		orderGoodsExtraInfoMapper.updateByPrimaryKeySelective(updateOrderGoodsExtraInfo);
		
		//更新订单购买证明
		List<OrderImageAddAO> purchaseProofList = editAO.getPurchaseProofList();
		if(!CommonUtils.isEmpty(purchaseProofList)) {
			List<OrderImage> orderImageList = new ArrayList<>();
			for(OrderImageAddAO orderImageAddAO : purchaseProofList) {
				OrderImage orderImage = new OrderImage();
				orderImage.setOrderId(orderId);
				orderImage.setType(orderImageAddAO.getType());
				orderImage.setPath(orderImageAddAO.getPath());
				orderImage.setCreateTime(time);
				orderImage.setUpdateTime(time);
				orderImageList.add(orderImage);
			}
			//批量新增
			orderImageMapper.insertBatch(orderImageList);
			//删除无效数据
			orderImageMapper.deleteByUpdateTime(orderId, OrderImageType.PURCHASE_PROOF, time);
		}
		
		//更新客户信息
		Customer updateCustomer = new Customer();
		BeanUtils.copyProperties(editAO, updateCustomer);
		updateCustomer.setId(customerId);
		updateCustomer.setUpdateTime(time);
		customerMapper.updateByPrimaryKeySelective(updateCustomer);
		
		//更新客户联系人信息 
    	List<CustomerContactAddAO> contactList = editAO.getContactList();
    	if(!CommonUtils.isEmpty(contactList)) {
    		List<CustomerContact> customerContactList = new ArrayList<>();
    		for(CustomerContactAddAO customerContactAddAO : contactList) {
    			CustomerContact customerContact = new CustomerContact();
    			BeanUtils.copyProperties(customerContactAddAO, customerContact);
    			customerContact.setCustomerId(customerId);
    			customerContact.setCreateTime(time);
    			customerContact.setUpdateTime(time);
    			customerContactList.add(customerContact);
    		}
    		//批量新增
    		customerContactMapper.insertBatch(customerContactList);
    		//删除无效数据
    		customerContactMapper.deleteByUpdateTime(customerId, time);
    	}
    	
    	//更新客户房产证明图片
    	List<CustomerImageAddAO> housePropertyProofList = editAO.getHousePropertyProofList();
    	if(!CommonUtils.isEmpty(housePropertyProofList)) {
    		List<CustomerImage> customerImageList = new ArrayList<>();
    		for(CustomerImageAddAO customerImageAddAO : housePropertyProofList) {
    			CustomerImage customerImage = new CustomerImage();
    			BeanUtils.copyProperties(customerImageAddAO, customerImage);
    			customerImage.setCustomerId(customerId);
    			customerImage.setCreateTime(time);
    			customerImage.setUpdateTime(time);
    			customerImageList.add(customerImage);
    		}
    		//批量新增
    		customerImageMapper.insertBatch(customerImageList);
    		//删除无效数据
    		customerImageMapper.deleteByUpdateTime(customerId, CustomerImageType.HOUSE_PROPERTY_PROOF, time);
    	}
    	
    	//更新客户结婚证明图片
    	List<CustomerImageAddAO> marriageProofList = editAO.getMarriageProofList();
    	if(!CommonUtils.isEmpty(marriageProofList)) {
    		List<CustomerImage> customerImageList = new ArrayList<>();
    		for(CustomerImageAddAO customerImageAddAO : marriageProofList) {
    			CustomerImage customerImage = new CustomerImage();
    			BeanUtils.copyProperties(customerImageAddAO, customerImage);
    			customerImage.setCustomerId(customerId);
    			customerImage.setCreateTime(time);
    			customerImage.setUpdateTime(time);
    			customerImageList.add(customerImage);
    		}
    		//批量新增
    		customerImageMapper.insertBatch(customerImageList);
    		//删除无效数据
    		customerImageMapper.deleteByUpdateTime(customerId, CustomerImageType.MARRIAGE_PROOF, time);
    	}
		
		
		return Result.success("编辑保存订单成功", orderId);
	}

	@Override
	public OrderAddInfoDisplayVO getOrderDisplayInfo(Long orderId) {
		
		OrderAddInfoDisplayVO orderAddInfoDisplayVO = orderMapper.selectOrderAddInfoDisplayVO(orderId);
		state(orderAddInfoDisplayVO != null, "查询订单信息异常");
		Long customerId = orderAddInfoDisplayVO.getCustomerId();
		
		//查询订单购买证明
		List<OrderImageListVO> purchaseProofList = orderImageMapper.selectOrderImageListByOrderId(orderId, OrderImageType.PURCHASE_PROOF);
		
		//查询客户联系人
		List<CustomerContactInfoVO> contactList = customerContactMapper.selectCustomerContactInfoByCustomerId(customerId);
		contactList.stream().forEach(c -> {
			c.setRelationshipText(c.getRelationship().getText());
		});
		
		//查询客户房产证明
		List<CustomerImageListVO> housePropertyProofList = customerImageMapper.selectCustomerImageListByCustomerId(customerId, CustomerImageType.HOUSE_PROPERTY_PROOF);
		
		//查询客户结婚证明
		List<CustomerImageListVO> marriageProofList = customerImageMapper.selectCustomerImageListByCustomerId(customerId, CustomerImageType.MARRIAGE_PROOF);
		
		orderAddInfoDisplayVO.setPurchaseProofList(purchaseProofList);
		orderAddInfoDisplayVO.setContactList(contactList);
		orderAddInfoDisplayVO.setHousePropertyProofList(housePropertyProofList);
		orderAddInfoDisplayVO.setMarriageProofList(marriageProofList);
		
		return orderAddInfoDisplayVO;
	}

    @Override
    public PageBean<OrderListVO> selectOrderList(OrderListQuery query) {

		query.setProductIdsList(dictService.selectProductIdsListInCache());

		int total = orderMapper.selectOrderListCount(query);
		List<OrderListVO> list = new ArrayList<>();
		if(total > 0) {
			query.startPage();
			list = orderMapper.selectOrderList(query);
			list.stream().forEach(o -> {

				o.setFeeRate(CommonUtils.isEmpty(o.getFeeRateStr()) ? BigDecimal.ZERO : new BigDecimal(o.getFeeRateStr()).multiply(new BigDecimal(100)));
				o.setPercentage(CommonUtils.isEmpty(o.getPercentageStr()) ? BigDecimal.ZERO : new BigDecimal(o.getPercentageStr()).multiply(new BigDecimal(100)));
				o.setFeeRateStr(null);
				o.setPercentageStr(null);
				o.setBankReceiveAcct(CommonUtils.bankCardAccountFormat(o.getBankReceiveAcct()));
				if(Constants.JYD_PRODUCTID.equals(o.getProductId())) {
					o.setOrderProductType("jyd");
				}else if(Constants.XSS_PRODUCTID.equals(o.getProductId()) || Constants.XXSC_PRODUCTID.equals(o.getProductId())) {
					o.setOrderProductType("xss_xxsc");
				}

			});
		}
        return new PageBean<>(list, total);
    }

	@Override
	public OrderDetailVO selectOrderDetailVO(Long orderId) {

		OrderDetailVO detailVO = orderMapper.selectOrderDetailVO(orderId);
		state(detailVO != null, "查询订单信息异常");
		detailVO.setBankReceiveAcct(CommonUtils.bankCardAccountFormat(detailVO.getBankReceiveAcct()));

		if(Constants.JYD_PRODUCTID.equals(detailVO.getProductId())) {
			detailVO.setOrderProductType("jyd");

		}else if(Constants.XSS_PRODUCTID.equals(detailVO.getProductId()) || Constants.XXSC_PRODUCTID.equals(detailVO.getProductId())) {
			detailVO.setOrderProductType("xss_xxsc");
			if(!CommonUtils.isEmpty(detailVO.getLoanTime())) {
				detailVO.setMonthlyRepayDate(detailVO.getLoanTime().substring(8, 10));
				detailVO.setLoanTime(null);
			}
			if(!CommonUtils.isEmpty(detailVO.getFeeRate())) {
				detailVO.setFeeRateBd(new BigDecimal(detailVO.getFeeRate()).multiply(new BigDecimal(100)));
				detailVO.setFeeRate(null);
			}
			if(!CommonUtils.isEmpty(detailVO.getPercentage())) {
				detailVO.setPercentageBd(new BigDecimal(detailVO.getPercentage()).multiply(new BigDecimal(100)));
				detailVO.setPercentage(null);
			}
			//查询订单购买证明
			List<OrderImageListVO> purchaseProofList = orderImageMapper.selectOrderImageListByOrderId(orderId, OrderImageType.PURCHASE_PROOF);
			detailVO.setPurchaseProofList(purchaseProofList);

		}

		return detailVO;
	}

    @Override
	@Transactional
    public void saveApplyData(LoanApplyDataDTO applyDataDTO, ThirdSource thirdSource) {

		Date time = new Date();
		Long productId = 0L;
		Long orderId = 0L;
		Long customerId = Long.valueOf(applyDataDTO.getUserId());
		String loanId = applyDataDTO.getLoanId();

		//查询产品信息
		ProductInfoDTO productInfoDTO = productMapper.selectProductInfoByThirdSourceAndThirdProductType(thirdSource, applyDataDTO.getProductType());
		productId = productInfoDTO.getProductId();

		//先查询第三方唯一订单号
		OrderGoodsExtraInfo dbOrderGoodsExtraInfo = new OrderGoodsExtraInfo();
		dbOrderGoodsExtraInfo.setThirdLoanId(loanId);
		dbOrderGoodsExtraInfo = orderGoodsExtraInfoMapper.selectOne(dbOrderGoodsExtraInfo);

		//查询客户是否存在
		Customer dbCustomer = customerMapper.selectByPrimaryKey(customerId);

		if(dbOrderGoodsExtraInfo == null && dbCustomer != null) {
			//如果第三方订单为空，并且客户不为空，则新增订单
			//新增订单
			Order newOrder = new Order();
			newOrder.setCustomerId(customerId);
			newOrder.setProductId(productId);
			newOrder.setCityId(1L);
			newOrder.setMobile(applyDataDTO.getMobileNum());
			newOrder.setPeriods(applyDataDTO.getApplyTerms());
			newOrder.setLoanAmount(BigDecimal.ZERO);
			newOrder.setRate(BigDecimal.ZERO);
			newOrder.setRepayType(RepayType.DEBX);
			newOrder.setOrderStatus(OrderStatus.APPLY_SUCCESS);
			newOrder.setApplyStatus(ApplyStatus.PROCESSING);
			newOrder.setUserId(0L);
			newOrder.setCommissionStatus(CommissionStatus.UN_NEED);
			newOrder.setWithholdStatus(OrderWithholdStatus.UN_NEED);
			newOrder.setCreateTime(time);
			newOrder.setUpdateTime(time);
			newOrder.setRejectType(OrderRejectType.UN_REJECT);
			//插入数据
			orderMapper.insertSelective(newOrder);
			//得到orderId
			orderId = newOrder.getId();

			//新增家具分期订单额外信息
			OrderGoodsExtraInfo newOrderGoodsExtraInfo = new OrderGoodsExtraInfo();
			newOrderGoodsExtraInfo.setOrderId(orderId);
			newOrderGoodsExtraInfo.setCustomerId(customerId);
			newOrderGoodsExtraInfo.setProductId(productId);
			newOrderGoodsExtraInfo.setBrandId(0L);
			newOrderGoodsExtraInfo.setStoreId(0L);
			newOrderGoodsExtraInfo.setThirdLoanId(loanId);
			newOrderGoodsExtraInfo.setThirdSource(thirdSource);
			newOrderGoodsExtraInfo.setThirdProductType(applyDataDTO.getProductType());
			newOrderGoodsExtraInfo.setApplyAmount(applyDataDTO.getApplyMoney());
			newOrderGoodsExtraInfo.setApplyPeriods(applyDataDTO.getApplyTerms());
			newOrderGoodsExtraInfo.setThirdStatus(applyDataDTO.getStatus());
			newOrderGoodsExtraInfo.setGoodsOrderStatus(GoodsOrderStatus.NO_BUY);
			OrderFinalStatusE finalStatus = orderStatusService.getOrderFinalStatus(thirdSource, productId, newOrderGoodsExtraInfo.getThirdStatus(), newOrderGoodsExtraInfo.getGoodsOrderStatus());
			state(finalStatus != null, "保存进件数据失败：订单状态判断异常。");
			newOrderGoodsExtraInfo.setFinalStatus(finalStatus);
			newOrderGoodsExtraInfo.setFinalStatusText(finalStatus.getText());
			newOrderGoodsExtraInfo.setCreateTime(time);
			newOrderGoodsExtraInfo.setUpdateTime(time);
			orderGoodsExtraInfoMapper.insertSelective(newOrderGoodsExtraInfo);

			//添加第一条订单审核数据类型，‘申请成功’
			String remark = "通过";
			SpringContextUtils.getBean(OrderAuditService.class).addOrderAuditRecord(orderId, Process.APPLY, AuditResult.PASS, remark);

		}

    }

	@Override
	@Transactional
	public Result saveLoanData(LoanDataDTO loanData, ThirdSource thirdSource) {

		if(CommonUtils.isEmpty(loanData.getStatus())) {
			log.info("云科订单[loanId = {}]状态为空异常！", loanData.getLoanId());
			return Result.fail("第三方订单状态为空异常！");
		}

		Date time = new Date();
		Long productId = 0L;
		Long orderId = 0L;
		Long customerId = 0L;
		String loanId = loanData.getLoanId();

		//先查询第三方唯一订单号
		OrderGoodsExtraInfo dbOrderGoodsExtraInfo = new OrderGoodsExtraInfo();
		dbOrderGoodsExtraInfo.setThirdLoanId(loanId);
		dbOrderGoodsExtraInfo = orderGoodsExtraInfoMapper.selectOne(dbOrderGoodsExtraInfo);
		if(dbOrderGoodsExtraInfo == null) {
			log.info("云科订单[loanId = {}]不存在", loanId);
			return Result.fail("云科订单[loanId = " + loanId + "]不存在");
		}

		//比较在库数据订单状态、我方查询或第三方推送结果的订单状态，是否相同，若相同，则不用更新数据，直接返回
		if(dbOrderGoodsExtraInfo.getThirdStatus().equals(loanData.getStatus())) {
			log.info("云科订单[loanId = {}]状态未发生变化，不更新在库数据，也无需发送微信消息通知", loanId);
			return Result.fail("云科订单状态未发生变化，不更新在库数据，也无需发送微信消息通知");
		}
		productId = dbOrderGoodsExtraInfo.getProductId();
		orderId = dbOrderGoodsExtraInfo.getOrderId();
		customerId = dbOrderGoodsExtraInfo.getCustomerId();

		if(!Constants.XSS_PRODUCTID.equals(productId) && !Constants.XXSC_PRODUCTID.equals(productId)) {
			//产品不是‘嘻唰唰’也不是‘薪享事成’
			log.info("云科订单[loanId = {}]产品异常", loanId);
			return Result.fail("云科订单[loanId = " + loanId + "]产品异常");
		}

		//更新 商品分期订单表信息 t_order_goods_extra_info
		dbOrderGoodsExtraInfo.setApplyAmount(loanData.getApplyMoney());
		dbOrderGoodsExtraInfo.setApplyPeriods(loanData.getApplyTerms());
		dbOrderGoodsExtraInfo.setDecisionAmount(loanData.getDecisionMoney());
		if(!CommonUtils.isEmpty(loanData.getDecisionTime())) {
			dbOrderGoodsExtraInfo.setDecisionTime(CommonUtils.timeStamp2Date(loanData.getDecisionTime()));
		}
		dbOrderGoodsExtraInfo.setFeeRate(loanData.getFee());
		dbOrderGoodsExtraInfo.setPercentage(loanData.getPercentage());
		dbOrderGoodsExtraInfo.setYearRate(loanData.getRate());
		dbOrderGoodsExtraInfo.setBankCardHolder(loanData.getCardHolder());
		dbOrderGoodsExtraInfo.setBankReceiveAcct(loanData.getReceiveAcct());
		dbOrderGoodsExtraInfo.setThirdStatus(loanData.getStatus());
		OrderFinalStatusE finalStatus = orderStatusService.getOrderFinalStatus(thirdSource, productId, dbOrderGoodsExtraInfo.getThirdStatus(), dbOrderGoodsExtraInfo.getGoodsOrderStatus());
		if(finalStatus == null) {
			return Result.fail("保存贷款数据失败：订单状态判断异常。");
		}
		dbOrderGoodsExtraInfo.setFinalStatus(finalStatus);
		dbOrderGoodsExtraInfo.setFinalStatusText(finalStatus.getText());
		dbOrderGoodsExtraInfo.setUpdateTime(time);
		orderGoodsExtraInfoMapper.updateByPrimaryKeySelective(dbOrderGoodsExtraInfo);

		//更新 订单表信息 t_order
		Order updateOrder = new Order();
		updateOrder.setId(orderId);
		updateOrder.setMobile(loanData.getMobileNum());
		updateOrder.setLoanAmount(loanData.getLoanMoneyAct());
		updateOrder.setPeriods(loanData.getApplyTerms());
		if(!CommonUtils.isEmpty(loanData.getRate())) {
			BigDecimal rate = new BigDecimal(loanData.getRate()).multiply(new BigDecimal(100)).divide(new BigDecimal(12), 2, RoundingMode.HALF_UP);
			updateOrder.setRate(rate);
		}
		if(!CommonUtils.isEmpty(loanData.getMoneyHandOutTime())) {
			updateOrder.setLoanTime(CommonUtils.timeStamp2Date(loanData.getMoneyHandOutTime()));
		}
		//对应的 ppj 订单审核流程状态
		if(!CommonUtils.isEmpty(loanData.getStatus())) {
			if("3".equals(loanData.getStatus())) {
				//云科状态为-审批通过，则 ppj 状态对应为 初审通过
				updateOrder.setOrderStatus(OrderStatus.FIRST_AUDIT_SUCCESS);
				updateOrder.setApplyStatus(ApplyStatus.PROCESSING);
				//添加审核记录
				String remark = "云科审批通过";
				SpringContextUtils.getBean(OrderAuditService.class).addOrderAuditRecord(orderId, Process.FIRST_AUDIT, AuditResult.PASS, remark);
			}
			if("4".equals(loanData.getStatus())) {
				//云科状态为-审批拒绝，则 ppj 状态对应为 初审拒绝
				updateOrder.setOrderStatus(OrderStatus.FIRST_AUDIT_FAIL);
				updateOrder.setApplyStatus(ApplyStatus.REJECT);
				updateOrder.setRejectType(OrderRejectType.FIRST_AUDIT_FAIL);
				updateOrder.setRejectReason("云科审批拒绝");
				//添加审核记录
				String remark = "云科审批拒绝";
				SpringContextUtils.getBean(OrderAuditService.class).addOrderAuditRecord(orderId, Process.FIRST_AUDIT, AuditResult.REJECT, remark);
			}
			if("6".equals(loanData.getStatus())) {
				//云科状态为-放款成功，则 ppj 状态对应为 放款成功
				updateOrder.setOrderStatus(OrderStatus.LOAN_SUCCESS);
				updateOrder.setApplyStatus(ApplyStatus.PASS);
				//添加审核记录
				String remark = "云科放款成功";
				SpringContextUtils.getBean(OrderAuditService.class).addOrderAuditRecord(orderId, Process.LOAN, AuditResult.PASS, remark);
			}
			if("7".equals(loanData.getStatus())) {
				//云科状态为-放款失败，则 ppj 状态对应为 放款失败
				updateOrder.setOrderStatus(OrderStatus.LOAN_FAIL);
				updateOrder.setApplyStatus(ApplyStatus.REJECT);
				updateOrder.setRejectType(OrderRejectType.LOAN_FAIL);
				updateOrder.setRejectReason("云科放款失败");
				//添加审核记录
				String remark = "云科放款失败";
				SpringContextUtils.getBean(OrderAuditService.class).addOrderAuditRecord(orderId, Process.LOAN, AuditResult.REJECT, remark);
			}
		}
		updateOrder.setUpdateTime(time);
		orderMapper.updateByPrimaryKeySelective(updateOrder);

		//更新 客户信息 t_customer
		Customer updateCustomer = new Customer();
		updateCustomer.setId(customerId);
		updateCustomer.setName(loanData.getCustName());
		updateCustomer.setIdNo(loanData.getCustIdCard());
		updateCustomer.setSex(CommonUtils.getSexByIdNo(loanData.getCustIdCard()));
		updateCustomer.setEmail(loanData.getEmail());
		updateCustomer.setResideAddress(loanData.getAddress());
		updateCustomer.setCompanyName(loanData.getCompanyName());
		updateCustomer.setCompanyAddress(loanData.getCompanyAddress());
		updateCustomer.setCompanyPhone(loanData.getOfficePhone());
		updateCustomer.setWorkDept(loanData.getWorkDept());
		updateCustomer.setPositionName(loanData.getPositionName());
		updateCustomer.setMonthlyIncome(loanData.getMonthlyIncome());
		updateCustomer.setUpdateTime(time);
		customerMapper.updateByPrimaryKeySelective(updateCustomer);

		return Result.success("", finalStatus);
	}

	@Override
	@Transactional
	public void saveOrderGoodsExtraInfo(OrderGoodsExtraInfoSaveAO saveAO) {

		Date time = new Date();
		Long orderId = saveAO.getOrderId();
		Long brandId = saveAO.getBrandId();
		Long storeId = saveAO.getStoreId();

		//先查询分期订单
		OrderGoodsExtraInfo dbOrderGoodsExtraInfo = new OrderGoodsExtraInfo();
		dbOrderGoodsExtraInfo.setOrderId(orderId);
		dbOrderGoodsExtraInfo = orderGoodsExtraInfoMapper.selectOne(dbOrderGoodsExtraInfo);
		state(dbOrderGoodsExtraInfo != null, "分期订单不存在，数据异常");

		OrderGoodsExtraInfo updateOrderGoodsExtraInfo = new OrderGoodsExtraInfo();
		updateOrderGoodsExtraInfo.setId(dbOrderGoodsExtraInfo.getId());
		if(0 == saveAO.getBrandId().longValue()) {
			//前台品牌选择了‘其他’ brandId == 0
			updateOrderGoodsExtraInfo.setBrandId(0L);
			updateOrderGoodsExtraInfo.setStoreId(0L);
			updateOrderGoodsExtraInfo.setBrandName(saveAO.getBrandName());
			updateOrderGoodsExtraInfo.setStoreName(saveAO.getStoreName());
			updateOrderGoodsExtraInfo.setStoreContactWay(saveAO.getStoreContactWay());
		}else {
			//根据 brandId,storeId 获取 品牌、门店信息
			Brand dbBrand = brandMapper.selectByPrimaryKey(brandId);
			Store dbStore = storeMapper.selectByPrimaryKey(storeId);
			updateOrderGoodsExtraInfo.setBrandId(saveAO.getBrandId());
			updateOrderGoodsExtraInfo.setStoreId(saveAO.getStoreId());
			updateOrderGoodsExtraInfo.setBrandName(dbBrand.getName());
			updateOrderGoodsExtraInfo.setStoreName(dbStore.getName());
			updateOrderGoodsExtraInfo.setStoreContactWay(dbStore.getContactWay());
		}
		updateOrderGoodsExtraInfo.setReceiveAddress(saveAO.getReceiveAddress());
		//把商品订单更新为：2-审核中（已上传商品购买订单等信息）
		updateOrderGoodsExtraInfo.setGoodsOrderStatus(GoodsOrderStatus.AUDITING);
		//更新订单最终状态
		OrderFinalStatusE finalStatus = orderStatusService.getOrderFinalStatus(dbOrderGoodsExtraInfo.getThirdSource(), dbOrderGoodsExtraInfo.getProductId(), dbOrderGoodsExtraInfo.getThirdStatus(), updateOrderGoodsExtraInfo.getGoodsOrderStatus());
		state(finalStatus != null, "更新订单数据失败：订单状态判断异常。");
		updateOrderGoodsExtraInfo.setFinalStatus(finalStatus);
		updateOrderGoodsExtraInfo.setFinalStatusText(finalStatus.getText());
		updateOrderGoodsExtraInfo.setUpdateTime(time);
		orderGoodsExtraInfoMapper.updateByPrimaryKeySelective(updateOrderGoodsExtraInfo);

		//保存购买证明信息
		List<OrderImageAddAO> purchaseProofList = saveAO.getPurchaseProofList();
		if(!CommonUtils.isEmpty(purchaseProofList)) {
			List<OrderImage> orderImageList = new ArrayList<>();
			for(OrderImageAddAO orderImageAddAO : purchaseProofList) {
				OrderImage orderImage = new OrderImage();
				orderImage.setOrderId(orderId);
				orderImage.setType(orderImageAddAO.getType());
				orderImage.setPath(orderImageAddAO.getPath());
				orderImage.setCreateTime(time);
				orderImage.setUpdateTime(time);
				orderImageList.add(orderImage);
			}
			//批量新增
			orderImageMapper.insertBatch(orderImageList);
			//删除无效数据
			orderImageMapper.deleteByUpdateTime(orderId, OrderImageType.PURCHASE_PROOF, time);
		}

	}

    @Override
    @Transactional
    public Result doConfirmSubmitOrder(ConfirmSubmitOrderAO confirmSubmitOrderAO, Long customerId) {

        Date time = new Date();
		//先检查客户是否已完成实名实人认证
		CustomerIdCardAuthRecord dbCustomerIdCardAuthRecord = new CustomerIdCardAuthRecord();
		dbCustomerIdCardAuthRecord.setCustomerId(customerId);
		dbCustomerIdCardAuthRecord = customerIdCardAuthRecordMapper.selectOne(dbCustomerIdCardAuthRecord);
		if(dbCustomerIdCardAuthRecord == null) {
			//如果为空，说明客户未进行过身份证图片信息上传ocr识别
			return Result.fail("客户未完成实名实人验证", ResultCode.CUSTOMER_ID_CARD_UNAUTH);
		}
		//不为空
		if(!CustomerIdCardAuthStatus.AUTH_SUCCESS.equals(dbCustomerIdCardAuthRecord.getAuthStatus())) {
			return Result.fail("客户未完成实名实人验证", ResultCode.CUSTOMER_ID_CARD_UNAUTH);
		}

		//检验是否有在途订单
//		OrderGoodsExtraInfo dbOrderGoodsExtraInfo1 = new OrderGoodsExtraInfo();
//		dbOrderGoodsExtraInfo1.setCustomerId(customerId);
//		dbOrderGoodsExtraInfo1.setProductId(Constants.JYD_PRODUCTID);
//		int count = orderGoodsExtraInfoMapper.selectCount(dbOrderGoodsExtraInfo1);
//		if(count != 0) {
//			return Result.fail("您已有在途订单，不可再次申请。");
//		}


		//客户已完成实名认证，请求云科，获取客户的准入额度，并返回loanId
        AdmittanceAndGetCreditsParamDTO paramDTO = customerIdCardAuthRecordMapper.selectAdmittanceAndGetCreditsParamDTO(customerId);
        if(paramDTO == null) {
            return Result.fail("获取准入额度请求参数异常");
        }
        paramDTO.setApplyMoney(confirmSubmitOrderAO.getApplyAmount());
        paramDTO.setLoanTerm(confirmSubmitOrderAO.getApplyPeriods());
        //查询联系人参数
        List<CustomerContactInfoVO> contactList = customerContactMapper.selectCustomerContactInfoByCustomerId(customerId);
        if(CommonUtils.isEmpty(contactList)) {
            return Result.fail("获取准入额度请求参数[联系人信息]异常");
        }
        List<ContactDTO> contact = new ArrayList<>();
        for(CustomerContactInfoVO bean : contactList) {
            ContactDTO contactDTO = new ContactDTO();
            contactDTO.setRelationCode(bean.getRelationship().getCode());
            contactDTO.setRelationName(bean.getRelationship().getText());
            contactDTO.setContactName(bean.getName());
            contactDTO.setContactMobile(bean.getMobile());
            contact.add(contactDTO);
        }
        paramDTO.setContact(contact);
        //查询房屋信息参数
        HouseInfoDTO houseInfoDTO = customerHouseInfoMapper.selectHouseInfoDTO(customerId);
        if(houseInfoDTO == null) {
            return Result.fail("获取准入额度请求参数[房屋信息]异常");
        }
		houseInfoDTO.setHouseValue(String.valueOf(new BigDecimal(10000).multiply(new BigDecimal(houseInfoDTO.getHouseValue()))));
        paramDTO.setHouseInfo(houseInfoDTO);

        //调用获取准入额度api
        Result<Map<String, Object>> result = fujueApiService.admittanceAndGetCredits(paramDTO);
        if(!result.isOk()) {
            return result;
        }
        //对返回数据进行 RSA解密
        Map<String, Object> bodyMap = result.getData();
        String encryptData = String.valueOf(bodyMap.get("data"));
        log.info("客户获取准入额度 api，返回参数data密文：{}", encryptData);
        String decryptData = RSAUtils.privateDecrypt(encryptData, Constants.FUJUE_RSA_PRIVATE_KEY);
        log.info("客户获取准入额度 api，返回参数data明文：{}", decryptData);
        //解析data
        Map<String, Object> dataMap = JsonObjectMapper.read(decryptData, Map.class);
        //得到loanId
        String loanId = String.valueOf(dataMap.get("loanId"));

        //先查询，以防重复
		OrderGoodsExtraInfo dbOrderGoodsExtraInfo = new OrderGoodsExtraInfo();
		dbOrderGoodsExtraInfo.setThirdLoanId(loanId);
		dbOrderGoodsExtraInfo = orderGoodsExtraInfoMapper.selectOne(dbOrderGoodsExtraInfo);
		if(dbOrderGoodsExtraInfo == null) {
			Long productId = Constants.JYD_PRODUCTID;
			Long orderId = 0L;
			//生成订单
			Order newOrder = new Order();
			newOrder.setCustomerId(customerId);
			newOrder.setProductId(productId);
			newOrder.setCityId(1L);
			newOrder.setMobile(paramDTO.getMobileNo());
			newOrder.setPeriods(paramDTO.getLoanTerm());
			newOrder.setLoanAmount(BigDecimal.ZERO);
			newOrder.setRate(BigDecimal.ZERO);
			newOrder.setRepayType(RepayType.DEBX);
			newOrder.setOrderStatus(OrderStatus.APPLY_SUCCESS);
			newOrder.setApplyStatus(ApplyStatus.PROCESSING);
			newOrder.setUserId(0L);
			newOrder.setCommissionStatus(CommissionStatus.UN_NEED);
			newOrder.setWithholdStatus(OrderWithholdStatus.UN_NEED);
			newOrder.setCreateTime(time);
			newOrder.setUpdateTime(time);
			newOrder.setRejectType(OrderRejectType.UN_REJECT);
			//插入数据
			orderMapper.insertSelective(newOrder);
			//得到orderId
			orderId = newOrder.getId();

			//新增家具分期订单额外信息
			OrderGoodsExtraInfo newOrderGoodsExtraInfo = new OrderGoodsExtraInfo();
			newOrderGoodsExtraInfo.setOrderId(orderId);
			newOrderGoodsExtraInfo.setCustomerId(customerId);
			newOrderGoodsExtraInfo.setProductId(productId);
			newOrderGoodsExtraInfo.setBrandId(0L);
			newOrderGoodsExtraInfo.setStoreId(0L);
			newOrderGoodsExtraInfo.setThirdLoanId(loanId);
			newOrderGoodsExtraInfo.setThirdSource(ThirdSource.YUNKEDAI);
			newOrderGoodsExtraInfo.setThirdProductType(paramDTO.getProdCode());
			newOrderGoodsExtraInfo.setApplyAmount(paramDTO.getApplyMoney());
			newOrderGoodsExtraInfo.setApplyPeriods(paramDTO.getLoanTerm());
			newOrderGoodsExtraInfo.setInterestType(confirmSubmitOrderAO.getInterestType());
			newOrderGoodsExtraInfo.setThirdStatus("A001");
			newOrderGoodsExtraInfo.setGoodsOrderStatus(GoodsOrderStatus.NO_BUY);
			newOrderGoodsExtraInfo.setFinalStatus(OrderFinalStatusE.ADMISSION_AUDITING);
			newOrderGoodsExtraInfo.setFinalStatusText(OrderFinalStatusE.ADMISSION_AUDITING.getText());
			newOrderGoodsExtraInfo.setCreateTime(time);
			newOrderGoodsExtraInfo.setUpdateTime(time);
			orderGoodsExtraInfoMapper.insertSelective(newOrderGoodsExtraInfo);

			//添加第一条订单审核数据类型，‘申请成功’
			String remark = "通过";
			SpringContextUtils.getBean(OrderAuditService.class).addOrderAuditRecord(orderId, Process.APPLY, AuditResult.PASS, remark);
		}

        return Result.success("提交订单成功");
    }

    @Override
    public OrderImageUploadStatusVO queryOrderImageUploadStatus(Long orderId) {

		OrderImageUploadStatusVO statusVO = new OrderImageUploadStatusVO();

		List<OrderImageType> imageTypeList = orderImageMapper.selectOrderImageTypeListByOrderId(orderId);
		imageTypeList.stream().forEach(t -> {
			switch (t) {
				case SCENE_IMAGE:
					statusVO.setSceneImage(true);
					break;
				case MORTGAGE_CONTRACT:
					statusVO.setMortgageContract(true);
					break;
				case HOUSE_PURCHASE_CONTRACT:
					statusVO.setHousePurchaseContract(true);
					break;
				case CHADANG_CERTIFICATE:
					statusVO.setChadangCertificate(true);
					break;
				case GOODS_PURCHASE_CONTRACT:
					statusVO.setGoodsPurchaseContract(true);
					break;
				case HOUSE_PROPERTY_CERTIFICATE:
					statusVO.setHousePropertyCertificate(true);
					break;
				case CREDIT_YINDING_AUTHORIZATION:
					statusVO.setCreditYindingAuthorization(true);
					break;
				case HAND_HOLD_ID_CARD:
					statusVO.setHandHoldIdCard(true);
					break;
				case OTHER:
					statusVO.setOther(true);
					break;
				default:
					break;
			}
		});

		return statusVO;
    }

	@Override
	public List<OrderImageListVO> getOrderImageList(Long orderId, OrderImageType orderImageType) {

		List<OrderImageListVO> orderImageList = orderImageMapper.selectOrderImageListByOrderId(orderId, orderImageType);

		return orderImageList;
	}

	@Override
	@Transactional
	public void doSaveOrderImage(OrderImageSaveAO saveAO) {

		Date time = new Date();

		List<OrderImageAddAO> imageList = saveAO.getImageList();
		if(!CommonUtils.isEmpty(imageList)) {
			List<OrderImage> orderImageList = new ArrayList<>();
			for(OrderImageAddAO addAO : imageList) {
				OrderImage newOrderImage = new OrderImage();
				newOrderImage.setOrderId(saveAO.getOrderId());
				newOrderImage.setType(saveAO.getOrderImageType());
				newOrderImage.setName(addAO.getName());
				newOrderImage.setPath(addAO.getPath());
				newOrderImage.setCreateTime(time);
				newOrderImage.setUpdateTime(time);
				orderImageList.add(newOrderImage);
			}
			//批量新增
			orderImageMapper.insertBatch(orderImageList);
			//删除无效数据
			orderImageMapper.deleteByUpdateTime(saveAO.getOrderId(), saveAO.getOrderImageType(), time);
		}

	}

    @Override
    public AddAttachmentParamDTO getAddAttachmentParam(Long orderId) {

		//查询loanId
		OrderGoodsExtraInfo dbOrderGoodsExtraInfo = new OrderGoodsExtraInfo();
		dbOrderGoodsExtraInfo.setOrderId(orderId);
		dbOrderGoodsExtraInfo = orderGoodsExtraInfoMapper.selectOne(dbOrderGoodsExtraInfo);
		state(dbOrderGoodsExtraInfo != null, "订单数据异常");

		//查询订单附件资料数组
		List<OrderImageListVO> orderImageList = orderImageMapper.selectAddAttachmentParam(orderId);
		state(!CommonUtils.isEmpty(orderImageList), "订单附件资料数据异常");
		List<AttachmentDTO> attachment = new ArrayList<>();
		for(OrderImageListVO bean : orderImageList) {
			AttachmentDTO attachmentDTO = new AttachmentDTO();
			attachmentDTO.setFileType(bean.getType().getCode());
			attachmentDTO.setFileUrl(bean.getSrc());
			attachmentDTO.setFileName(bean.getName());
			attachment.add(attachmentDTO);
		}

		//返回
		AddAttachmentParamDTO paramDTO = new AddAttachmentParamDTO();
		paramDTO.setLoanId(dbOrderGoodsExtraInfo.getThirdLoanId());
		paramDTO.setAttachment(attachment);

		return paramDTO;
    }

	@Override
	@Transactional
	public void updateOrderFinalStatus(Long orderId, OrderFinalStatusE finalStatus) {

		OrderGoodsExtraInfo dbOrderGoodsExtraInfo = new OrderGoodsExtraInfo();
		dbOrderGoodsExtraInfo.setOrderId(orderId);
		dbOrderGoodsExtraInfo = orderGoodsExtraInfoMapper.selectOne(dbOrderGoodsExtraInfo);
		state(dbOrderGoodsExtraInfo != null, "订单数据异常");

		OrderGoodsExtraInfo update = new OrderGoodsExtraInfo();
		update.setId(dbOrderGoodsExtraInfo.getId());
		update.setFinalStatus(finalStatus);
		update.setFinalStatusText(finalStatus.getText());
		update.setUpdateTime(new Date());
		orderGoodsExtraInfoMapper.updateByPrimaryKeySelective(update);

	}

	@Override
	@Transactional
	public Result doUpdateOrderData(NotifyDataDTO notifyData) {

		if(CommonUtils.isEmpty(notifyData.getStatus())) {
			log.info("云科订单[loanId = {}]状态为空异常！", notifyData.getLoanId());
			return Result.fail("第三方订单状态为空异常！");
		}

		Date time = new Date();
		String loanId = notifyData.getLoanId();

		//先查询第三方唯一订单号
		OrderGoodsExtraInfo dbOrderGoodsExtraInfo = new OrderGoodsExtraInfo();
		dbOrderGoodsExtraInfo.setThirdLoanId(loanId);
		dbOrderGoodsExtraInfo = orderGoodsExtraInfoMapper.selectOne(dbOrderGoodsExtraInfo);
		if(dbOrderGoodsExtraInfo == null) {
			log.info("云科订单[loanId = {}]不存在", loanId);
			return Result.fail("云科订单[loanId = " + loanId + "]不存在");
		}
		//若存在
		//比较在库数据订单状态、我方查询或第三方推送结果的订单状态，是否相同，若相同，则不用更新数据，直接返回
		if(dbOrderGoodsExtraInfo.getThirdStatus().equals(notifyData.getStatus())) {
			log.info("云科订单[loanId = {}]状态未发生变化，不更新在库数据，也无需发送微信消息通知", loanId);
			return Result.fail("云科订单状态未发生变化，不更新在库数据，也无需发送微信消息通知");
		}

		OrderGoodsExtraInfo updateDO = new OrderGoodsExtraInfo();
		updateDO.setId(dbOrderGoodsExtraInfo.getId());
		updateDO.setThirdLoanId(loanId);
		updateDO.setDecisionAmount(notifyData.getApproveMoney());
		updateDO.setDecisionTime(time);
		updateDO.setBankCardHolder(notifyData.getUserName());
		updateDO.setBankReceiveAcct(notifyData.getBankCradNum());
		updateDO.setBankName(notifyData.getBankName());
		updateDO.setBankMobile(notifyData.getMobileNum());
		updateDO.setThirdStatus(notifyData.getStatus());
		OrderFinalStatusE finalStatus = orderStatusService.getOrderFinalStatus(dbOrderGoodsExtraInfo.getProductId(), notifyData.getStatus(), notifyData.getRejectCode());
		if(finalStatus == null) {
			return Result.fail("更新数据失败：订单状态判断异常。");
		}
		updateDO.setFinalStatus(finalStatus);
		updateDO.setFinalStatusText(finalStatus.getText());
		if(!CommonUtils.isEmpty(notifyData.getRejectCode())) {
			updateDO.setRejectReason(notifyData.getRejectCode() + notifyData.getRejectReason());
		}
		updateDO.setUpdateTime(time);
		orderGoodsExtraInfoMapper.updateByPrimaryKeySelective(updateDO);

		//更新 订单表信息 t_order
		if(OrderFinalStatusE.REPAYING.equals(finalStatus) || OrderFinalStatusE.LOAN_SUCCESS.equals(finalStatus)
                || OrderFinalStatusE.LOAN_FAIL.equals(finalStatus)) {

			Order updateOrder = new Order();
			updateOrder.setId(dbOrderGoodsExtraInfo.getOrderId());
			if(OrderFinalStatusE.REPAYING.equals(finalStatus) || OrderFinalStatusE.LOAN_SUCCESS.equals(finalStatus)) {
				//云科状态为-放款成功，则 ppj 状态对应为 放款成功
				updateOrder.setLoanAmount(notifyData.getApproveMoney());
				updateOrder.setLoanTime(time);
				updateOrder.setApplyStatus(ApplyStatus.PASS);
			}
			if(OrderFinalStatusE.LOAN_FAIL.equals(finalStatus)) {
				//云科状态为-放款失败，则 ppj 状态对应为 放款失败
				updateOrder.setApplyStatus(ApplyStatus.REJECT);
				updateOrder.setRejectType(OrderRejectType.LOAN_FAIL);
				updateOrder.setRejectReason("云科放款失败");
			}
			updateOrder.setUpdateTime(time);
			orderMapper.updateByPrimaryKeySelective(updateOrder);
		}

		//保存客户-我的银行卡
		if(!CommonUtils.isEmpty(notifyData.getBankCradNum())) {
			CustomerBank dbCustomerBank = new CustomerBank();
			dbCustomerBank.setCustomerId(dbOrderGoodsExtraInfo.getCustomerId());
			dbCustomerBank.setBankCardNum(notifyData.getBankCradNum());
			int count = customerBankMapper.selectCount(dbCustomerBank);
			if(count <= 0) {
				CustomerBank newCustomerBank = new CustomerBank();
				newCustomerBank.setCustomerId(dbOrderGoodsExtraInfo.getCustomerId());
				newCustomerBank.setBankCardNum(notifyData.getBankCradNum());
				newCustomerBank.setBankName(notifyData.getBankName());
				newCustomerBank.setBankMobile(notifyData.getMobileNum());
				newCustomerBank.setCreateTime(time);
				newCustomerBank.setUpdateTime(time);
				customerBankMapper.insertSelective(newCustomerBank);
			}
		}


		return Result.success("更新订单数据成功", finalStatus);
	}

    @Override
	@Transactional
    public void deleteAllOrderByMobile(String mobile) {
        orderGoodsExtraInfoMapper.deleteAllOrderByMobile(mobile);
        orderGoodsExtraInfoMapper.deleteAllOrderByMobile2(mobile);
        orderGoodsExtraInfoMapper.deleteAllOrderByMobile3(mobile);
        orderGoodsExtraInfoMapper.deleteAllOrderByMobile4(mobile);
    }

	@Override
	public OrderGoodsExtraInfo getOrderGoodsExtraInfoByOrderId(Long orderId) {

		OrderGoodsExtraInfo dbOrderGoodsExtraInfo = new OrderGoodsExtraInfo();
		dbOrderGoodsExtraInfo.setOrderId(orderId);
		dbOrderGoodsExtraInfo = orderGoodsExtraInfoMapper.selectOne(dbOrderGoodsExtraInfo);
		state(dbOrderGoodsExtraInfo != null, "查询订单数据异常");

		return dbOrderGoodsExtraInfo;
	}


}
